package com.changgou.filter;

import io.jsonwebtoken.Claims;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import com.changgou.util.JwtUtils;

import reactor.core.publisher.Mono;

/**
 * 用户鉴权
 * 
 * @author gaofeng
 * @date 2025年04月30日 23:04
 */
@Component
public class AuthorizationFilter implements GlobalFilter, Ordered {
    private static final String AUTHORIZATION = "Authorization";

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        String token = request.getHeaders().getFirst(AUTHORIZATION);
        if (StringUtils.isBlank(token)) {
            token = request.getQueryParams().getFirst(AUTHORIZATION);
        }

        if (StringUtils.isBlank(token)) {
            HttpCookie cookie = request.getCookies().getFirst(AUTHORIZATION);
            if (cookie != null) {
                token = cookie.getValue();
            }
        }

        if (StringUtils.isBlank(token)) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);

            return response.setComplete();
        }

        try {
            Claims claims = JwtUtils.parseJwt(token);
            request.mutate().header(AUTHORIZATION, claims.toString());
        } catch (Exception e) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}